import React, { useEffect, useState, useRef } from 'react'
import {
    Text,
    View,
    Button,
    TouchableOpacity,
    SafeAreaView,
    TextInput,
    StyleSheet,
    Animated,
    Dimensions,
    Image,
    ScrollView,
    ActivityIndicator,
    FlatList,
    Alert
} from 'react-native'
import { useNavigation, useRoute } from '@react-navigation/native'
import Icon from 'react-native-vector-icons/FontAwesome';
import PagerView from 'react-native-pager-view';
import AsyncStorage from '@react-native-async-storage/async-storage';

const { width: screenWidth, height: screenHeight } = Dimensions.get('window');

const PAGE_CHAR_COUNT = 800; // 每页字符数，可根据实际体验调整

const BookReading = () => {
    const navigation = useNavigation();
    const route = useRoute();
    const { bookId, chapterId } = route.params || {};
    const [chapter, setChapter] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [pages, setPages] = useState([]);
    const [currentPage, setCurrentPage] = useState(0);
    const [menuVisible, setMenuVisible] = useState(false);
    const [menuAnimation] = useState(new Animated.Value(-300));
    const [chapterList, setChapterList] = useState([]);
    const [searchText, setSearchText] = useState('');

    // 拉取章节内容
    useEffect(() => {
        const fetchChapter = async () => {
            setLoading(true);
            setError(null);
            try {
                const token = await AsyncStorage.getItem('authToken');
                const response = await fetch(`http://124.222.104.145:8003/book/books/${bookId}/chapters/${chapterId}/`, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json',
                    },
                });
                const data = await response.json();
                if (response.ok) {
                    setChapter(data);
                    setPages(paginateContent(data.content || ''));
                } else {
                    setError(data.detail || '获取章节失败');
                }
            } catch (e) {
                setError('网络请求失败');
            } finally {
                setLoading(false);
            }
        };
        if (bookId && chapterId) fetchChapter();
    }, [bookId, chapterId]);

    // 拉取目录
    useEffect(() => {
        const fetchChapters = async () => {
            try {
                const response = await fetch(`http://124.222.104.145:8003/book/books/${bookId}`);
                const data = await response.json();
                setChapterList(Array.isArray(data.chapters) ? data.chapters : []);
            } catch { }
        };
        if (bookId) fetchChapters();
    }, [bookId]);

    // 分页函数
    function paginateContent(content) {
        if (!content) return [''];
        const result = [];
        let i = 0;
        while (i < content.length) {
            result.push(content.slice(i, i + PAGE_CHAR_COUNT));
            i += PAGE_CHAR_COUNT;
        }
        return result;
    }

    // 菜单动画
    const toggleMenu = () => {
        Animated.timing(menuAnimation, {
            toValue: menuVisible ? -300 : 0,
            duration: 300,
            useNativeDriver: true
        }).start();
        setMenuVisible(!menuVisible);
    };

    // 跳转到指定章节
    const jumpToChapter = (chap) => {
        setMenuVisible(false);
        navigation.replace('BookReading', { bookId, chapterId: chap.id });
    };

    // 跳转到指定页
    const jumpToPage = (pageIdx) => {
        setCurrentPage(pageIdx);
    };

    if (loading) {
        return (
            <View style={styles.loadingContainer}>
                <ActivityIndicator size="large" color="#70a1ff" />
            </View>
        );
    }
    if (error) {
        return (
            <View style={styles.errorContainer}>
                <Text style={styles.errorText}>{error}</Text>
            </View>
        );
    }
    if (!chapter) {
        return (
            <View style={styles.errorContainer}>
                <Text style={styles.errorText}>未找到章节内容</Text>
            </View>
        );
    }

    return (
        <SafeAreaView style={{ flex: 1, backgroundColor: '#f6f1eb' }}>
            {/* 顶部返回条 */}
            <View style={styles.header}>
                <TouchableOpacity onPress={() => navigation.goBack()}>
                    <Icon name="angle-left" size={30} color="#000" />
                </TouchableOpacity>
                <TouchableOpacity onPress={toggleMenu}>
                    <Icon name="bars" size={25} color="#555" />
                </TouchableOpacity>
            </View>

            {/* 章节标题 */}
            <Text style={styles.title}>{chapter.title}</Text>

            {/* 正文分页显示 */}
            <ScrollView style={[styles.contentContainer, { backgroundColor: '#fff', borderRadius: 16, margin: 10, padding: 20, elevation: 2 }]}>
                <Text style={styles.contentText}>{pages[currentPage]}</Text>
                <Text style={styles.pageInfo}>第 {currentPage + 1} 页 / 共 {pages.length} 页</Text>
            </ScrollView>

            {/* 上一页/下一页按钮 */}
            <View style={styles.pageNav}>
                <TouchableOpacity
                    onPress={() => jumpToPage(Math.max(currentPage - 1, 0))}
                    disabled={currentPage === 0}
                    style={[styles.pageBtn, currentPage === 0 && styles.pageBtnDisabled]}
                >
                    <Icon name="angle-left" size={22} color={currentPage === 0 ? '#ccc' : '#333'} />
                    <Text style={{ color: currentPage === 0 ? '#ccc' : '#333' }}>上一页</Text>
                </TouchableOpacity>
                <TouchableOpacity
                    onPress={() => jumpToPage(Math.min(currentPage + 1, pages.length - 1))}
                    disabled={currentPage === pages.length - 1}
                    style={[styles.pageBtn, currentPage === pages.length - 1 && styles.pageBtnDisabled]}
                >
                    <Text style={{ color: currentPage === pages.length - 1 ? '#ccc' : '#333' }}>下一页</Text>
                    <Icon name="angle-right" size={22} color={currentPage === pages.length - 1 ? '#ccc' : '#333'} />
                </TouchableOpacity>
            </View>

            {/* 目录侧边栏 */}
            <Animated.View style={[styles.menuContainer, { transform: [{ translateX: menuAnimation }] }]}>
                <TextInput
                    style={styles.searchInput}
                    placeholder="搜索目录..."
                    value={searchText}
                    onChangeText={setSearchText}
                />
                <FlatList
                    data={chapterList.filter(chap => chap.title.includes(searchText))}
                    keyExtractor={item => item.id.toString()}
                    renderItem={({ item }) => (
                        <TouchableOpacity
                            style={styles.chapterItem}
                            onPress={() => jumpToChapter(item)}
                        >
                            <Text numberOfLines={1}>{item.title}</Text>
                        </TouchableOpacity>
                    )}
                />
            </Animated.View>
            {/* 遮罩层，点击关闭目录 */}
            {menuVisible && (
                <TouchableOpacity
                    style={styles.overlay}
                    activeOpacity={1}
                    onPress={toggleMenu}
                />
            )}
        </SafeAreaView>
    );
}

const styles = StyleSheet.create({
    header: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingHorizontal: 20,
        paddingTop: 30,
        backgroundColor: '#f2f2f2',
        paddingBottom: 10,
    },
    title: {
        fontSize: 22,
        fontWeight: 'bold',
        color: '#333',
        textAlign: 'center',
        marginVertical: 16,
        fontFamily: 'Georgia',
    },
    contentContainer: {
        flex: 1,
        paddingHorizontal: 20,
    },
    contentText: {
        fontSize: 19,
        color: '#222',
        lineHeight: 32,
        marginBottom: 20,
        fontFamily: 'Georgia',
        letterSpacing: 0.5,
    },
    pageInfo: {
        alignSelf: 'center',
        color: '#a67c52',
        fontSize: 15,
        backgroundColor: '#f7ecd7',
        borderRadius: 10,
        paddingHorizontal: 16,
        paddingVertical: 5,
        marginBottom: 20,
        overflow: 'hidden',
        marginTop: 10,
        fontFamily: 'Georgia',
        elevation: 1,
        shadowColor: '#a67c52',
        shadowOffset: { width: 0, height: 1 },
        shadowOpacity: 0.08,
        shadowRadius: 2,
    },
    pageNav: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingHorizontal: 40,
        paddingVertical: 10,
        backgroundColor: '#fff',
    },
    pageBtn: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 8,
        borderRadius: 8,
        backgroundColor: '#f2f2f2',
    },
    pageBtnDisabled: {
        backgroundColor: '#eee',
    },
    menuContainer: {
        position: 'absolute',
        left: 0,
        top: 0,
        width: 260,
        height: '100%',
        backgroundColor: 'white',
        padding: 15,
        zIndex: 1000,
        shadowColor: '#000',
        shadowOffset: { width: 2, height: 0 },
        shadowOpacity: 0.1,
        shadowRadius: 5,
    },
    searchInput: {
        height: 40,
        borderColor: '#ddd',
        borderWidth: 1,
        borderRadius: 8,
        paddingHorizontal: 10,
        marginBottom: 15,
    },
    chapterItem: {
        paddingVertical: 12,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
    },
    overlay: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'rgba(0,0,0,0.1)',
        zIndex: 999,
    },
    loadingContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    errorContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    errorText: {
        color: '#ff4d4d',
        fontSize: 16,
    },
});

export default BookReading
